package com.xxwy.lifecycle.initialization;

import com.xxwy.lifecycle.bean.User;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.util.ObjectUtils;

/**
 * 回调接口实现.
 *
 * @author xxwy
 * @date 2021/7/23 0023
 */
public class MyInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {

//        /**
//         * 返回非null，则不使用spring ioc的反射生成对象，下面两个回调都不会执行。
//         */
//        @Override
//        public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
//            if (ObjectUtils.nullSafeEquals("user", beanName) && User.class.equals(beanClass)) {
//                return new User();
//            }
//            return null;
//        }
//
//        /**
//         * 返回false, property的赋值不会被执行（下面回调也不会执行）, 这里有bean对象可以随意处理。
//         *
//         */
//        @Override
//        public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
//            return !ObjectUtils.nullSafeEquals("user", beanName) || !User.class.equals(bean.getClass());
//        }

    /**
     * 属性赋值前置方法，
     */
    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
        if (ObjectUtils.nullSafeEquals("user", beanName) && User.class.equals(bean.getClass())) {
            MutablePropertyValues propertyValues = new MutablePropertyValues();
            // <property name="number" value="11" />
            propertyValues.addPropertyValue("number", "11");
            propertyValues.addPropertyValues(pvs);
            return propertyValues;
        }
        return pvs;
    }

    /**
     * 初始化前置方法： 返回null 不处理后续的postProcessorBeforeInitialization
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (ObjectUtils.nullSafeEquals("user", beanName) && User.class.equals(bean.getClass())) {
            ((User) bean).setAge(36);
            return bean;
        }
        return null;
    }
}
